package com.kvest.maptest.ui.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.Tile;
import com.google.android.gms.maps.model.TileOverlay;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
import com.kvest.maptest.R;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;

/**
 * Created with IntelliJ IDEA.
 * User: roman
 * Date: 9/4/13
 * Time: 9:29 AM
 * To change this template use File | Settings | File Templates.
 */
public class OSMMapActivity  extends FragmentActivity {
    private GoogleMap map;
    private TileOverlay tileOverlay;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_map);

        init();
    }

    private void init() {
        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        map.setMyLocationEnabled(true);
        map.setMapType(GoogleMap.MAP_TYPE_NONE);

        tileOverlay = map.addTileOverlay(new TileOverlayOptions().tileProvider(new OSMTileProvider()));
    }

    private static class OSMTileProvider implements TileProvider {
        @Override
        public Tile getTile(int x, int y, int zoom) {
            //create link
            String url = "http://a.tile.openstreetmap.org/" + zoom + "/" + x + "/" + y + ".png";
            Bitmap image = loadImage(url);
            if (image != null) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                image.compress(Bitmap.CompressFormat.PNG, 100, stream);
                Tile tile = new Tile(image.getWidth(), image.getHeight(), stream.toByteArray());
                return tile;
            }
                return NO_TILE;
        }
    }

    private  static BitmapFactory.Options opt = new BitmapFactory.Options();
    static {
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
    }

    private static Bitmap loadImage(String url)
    {
        try
        {
            InputStream is = (InputStream) new URL(url).getContent();
            Bitmap result = BitmapFactory.decodeStream(is, null, opt);
            return result;
        }
        catch (Exception e)
        {
            return null;
        }
    }

}
